<template>
    <Menu ref="sideMenu" :active-name="$route.name" :open-names="openNames" theme="dark" accordion width="auto" @on-select="changeMenu"
>
        <template v-for="item in menuList">
            <MenuItem v-if="item.children.length<=0" :name="item.children[0].name" :key="'menuitem' + item.name">
                <Icon :type="item.children[0].icon || item.icon" :size="iconSize" :key="'menuicon' + item.name"></Icon>
                <span class="layout-text" :key="'title' + item.name">{{ itemTitle(item.children[0]) }}</span>
            </MenuItem>
            <Submenu v-if="item.children.length >= 1" :name="item.name" :key="item.name">
                <template slot="title">
                    <Icon :type="item.icon" :size="iconSize" @click="ceshi(item)"></Icon>
                    <span class="layout-text">{{ itemTitle(item) }}</span>
                </template>
                <template v-for="child in item.children">
                    <MenuItem :name="child.name" :key="'menuitem' + child.name">
                        <Icon :type="child.icon" :size="iconSize" :key="'icon' + child.name"></Icon>
                        <span class="layout-text" :key="'title' + child.name">{{ itemTitle(child) }}</span>
                    </MenuItem>
                </template>
            </Submenu>
        </template>
    </Menu>
</template>

<script>
export default {
    name: 'sidebarMenu',
    inject:['reload'],
    props: {
        menuList: Array,
        iconSize: Number,
        openNames: {
            type: Array
        }
    },
    methods: {
        changeMenu (active) {
            this.$emit('on-change', active);
        },
        itemTitle (item) {
            if (typeof item.title === 'object') {
                return this.$t(item.title.i18n);
            } else {
                return item.title;
            }
        }
    },
    mounted () {
        this.open = [];
        this.openedNames = [];
        let nowActiveName = this.$refs.sideMenu.activeName;
        if (this.menuList &&　this.menuList.length > 0) {
            for (let iList = 0, iListLen = this.menuList.length; iList < iListLen; iList++) {
                for (let l = 0, lLen = this.menuList[iList].children.length; l < lLen; l++) {
                    if (nowActiveName === this.menuList[iList].children[l].name) {
                        this.open.push(this.menuList[iList].name);
                        this.openedNames.push(this.menuList[iList].name);
                    }
                }
            }
        }

        this.active = [];
        this.$nextTick((d) => {
            for (let i = 0, iLen = this.openedNames.length; i < iLen; i++) {
                this.$refs.sideMenu.updateOpenKeys(this.openedNames[i]);
            }

        })
    },
    updated () {
        this.$nextTick(() => {
            if (this.$refs.sideMenu) {
                this.$refs.sideMenu.updateOpened();
            }
        });
    }

};
</script>
